#include "net.h"

//服务器
int main()
{

	int fd;
	struct sockaddr_in soc;

	//创建套接字
	if( (fd = socket( AF_INET, SOCK_STREAM, 0)) < 0)
	{
		perror("socket");
		exit(1);
	}

	/* 填充结构体 */
	soc.sin_family = AF_INET;
	soc.sin_port = htons(PORT);
#if 1
	/* ipv4 */
	soc.sin_addr.s_addr = inet_addr(IP_ADDR4);

#else 

	/* ipv4 ipv6 都可以用 */
	if( (inet_pton(AF_INET, IP_ADDR, (void*)soc.sin_addr)) < 0)
	{
		perror("inet_pton");
		exit(0);
	}

#endif

	
	/* 绑定 */	
	if( (bind(fd, (struct sockaddr* )&soc, sizeof(soc)))< 0 )
	{

		perror("bind");
		exit(0);
	}

	/* 自动设置成被动 */
	if( (listen(fd, BACKLOG)) < 0)
	{
		perror("listen");
		exit(0);
	}
	printf ("Server starting....OK!\n");

	int newfd;
	/* 阻塞等待用户连接 */
	if( (newfd = accept(fd, NULL, NULL)) < 0)
	{
		perror("accept");
		exit(0);
	}


		/*5. 读写 */
	//..和newfd进行数据读写
	int ret = -1;
	char buf[BUFSI];
	while (1) {
		bzero (buf, BUFSI);
		do {
			ret = read (newfd, buf, BUFSI - 1);
		} while (ret < 0 && EINTR == errno);
		if (ret < 0) {

			perror ("read");
			exit (1);
		}
		if (!ret) {				//对方已经关闭
			break;
		}
		printf ("Receive data: %s\n", buf);

		if (!strncasecmp (buf, QUIT, strlen (QUIT))) {	//用户输入了quit字符
			printf ("Client is exiting!\n");
			break;
		}
	}

	/* 关闭文件和套接字 */
	close (newfd);

	close (fd);

}












